home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 1992 June: ROMin Holiday / ADC Developer CD (1992-06) (''ROMin Holiday'')_iso / Developer Connection - 06-1992.iso / Developer Essentials / DTS Sample Code / Snippets / Nets & Comm / Transition Queue Watcher / ATQWatcher.p < prev    next >
Encoding:
Text File  |  1992-01-30  |  55.6 KB  |  1,699 lines  |  [TEXT/MPS ]

  1. {------------------------------------------------------------------------------
  2. #
  3. #    Apple Macintosh Developer Technical Support
  4. #
  5. #    This sample program demonstrates the implementation of an
  6. #    AppleTalk Transition Queue to demonstrate the messages
  7. #    which get passed when transition events take place.
  8. #
  9. #    This sample program is based on the sample application
  10. #    TESample.p
  11. #
  12. #    MultiFinder-Aware Simple TextEdit Sample Application
  13. #
  14. #    ATQWatcher
  15. #
  16. #    ATQWatcher.p    -    Pascal Source
  17. #
  18. #    Copyright © Apple Computer, Inc. 1989-1992
  19. #    All rights reserved.
  20. #
  21. #                1.00                01/92
  22. #
  23. #    Components:
  24. #                ATQWatcher.p            Feb.  1, 1992
  25. #                ATQWatcherGlue.a    Feb.  1, 1992
  26. #                ATQWatcher.r            Feb.  1, 1992
  27. #                ATQWatcher.h            Feb.  1, 1992
  28. #                ATQWatcher.make        Feb.  1, 1992
  29. #
  30. # ATQWatcher implements a single TextEdit window for display
  31. # of messages occurring on the AppleTalkTransition Queue.  The 
  32. # following are a list of ways to generate Transition events.
  33. #
  34. # Launch ATQWatcher under multifinder and leave it in the
  35. # background.  Bring up the Chooser and shutdown and turn on
  36. # AppleTalk.  Bring ATQWatcher to the foreground and go to the
  37. # Control menu and select the "Refuse ATalk Close" item, then
  38. # try shutting down AppleTalk.  Also try using the Network cdev
  39. # to change the current AppleTalk connection.  
  40. #
  41. # With AppleTalk active, bring up the Sharing Setup cdev
  42. # and change the Macintosh name.  Bring ATQWatcher to the 
  43. # foreground and go to the Control menu and select the 
  44. # "Refuse ATalk Close" item, then try changing the
  45. # Macintosh Name.
  46. #
  47. # Establish a connection with the Remote Access program to
  48. # generate a Network Transition message.  Break the
  49. # connection.
  50. #
  51. # To generate a range change transition event, connect the system
  52. # to a network which includes a router.  Launch ATQWatcher, 
  53. # before starting up the router.
  54. #
  55. # Presently, there is no system means towards generating 
  56. # a speed transition event, however third party cdevs are
  57. # being released which toggle the 68040 cache on the Quadra
  58. # units on the fly.  If these cdev's have been written to generate
  59. # the 'sped' range change transition event, ATQWatcher will 
  60. # report the event.  To check it's operation, write a quick
  61. # program to make the
  62. # ATEvent(ATTransSpeedChange,nil);
  63. # call.
  64. #
  65. # The following are the original comments for TESample.
  66. #
  67. #    TESample is an example application that demonstrates how 
  68. #    to initialize the commonly used toolbox managers, operate 
  69. #    successfully under MultiFinder, handle desk accessories and 
  70. #    create, grow, and zoom windows. The fundamental TextEdit 
  71. #    toolbox calls and TextEdit autoscroll are demonstrated. It 
  72. #    also shows how to create and maintain scrollbar controls.
  73. #
  74. #    It does not by any means demonstrate all the techniques you 
  75. #    need for a large application. In particular, Sample does not 
  76. #    cover exception handling, multiple windows/documents, 
  77. #    sophisticated memory management, printing, or undo. All of 
  78. #    these are vital parts of a normal full-sized application.
  79. #
  80. #    This application is an example of the form of a Macintosh 
  81. #    application; it is NOT a template. It is NOT intended to be 
  82. #    used as a foundation for the next world-class, best-selling, 
  83. #    600K application. A stick figure drawing of the human body may 
  84. #    be a good example of the form for a painting, but that does not 
  85. #    mean it should be used as the basis for the next Mona Lisa.
  86. #
  87. #    We recommend that you review this program or Sample before 
  88. #    beginning a new application. Sample is a simple app. which doesn’t 
  89. #    use TextEdit or the Control Manager.
  90. #
  91. ------------------------------------------------------------------------------}
  92.  
  93.  
  94. PROGRAM ATQSample;
  95.  
  96.  
  97. {Segmentation strategy:
  98.  
  99.  This program consists of three segments. Main contains most of the code,
  100.  including the MPW libraries, and the main program. Initialize contains
  101.  code that is only used once, during startup, and can be unloaded after the
  102.  program starts. %A5Init is automatically created by the Linker to initialize
  103.  globals for the MPW libraries and is unloaded right away.}
  104.  
  105.  
  106. {SetPort strategy:
  107.  
  108.  Toolbox routines do not change the current port. In spite of this, in this
  109.  program we use a strategy of calling SetPort whenever we want to draw or
  110.  make calls which depend on the current port. This makes us less vulnerable
  111.  to bugs in other software which might alter the current port (such as the
  112.  bug (feature?) in many desk accessories which change the port on OpenDeskAcc).
  113.  Hopefully, this also makes the routines from this program more self-contained,
  114.  since they don't depend on the current port setting.}
  115.  
  116.  
  117. {Clipboard strategy:
  118.  
  119.  This program does not maintain a private scrap. Whenever a cut, copy, or paste
  120.  occurs, we import/export from the public scrap to TextEdit's scrap right away,
  121.  using the TEToScrap and TEFromScrap routines. If we did use a private scrap,
  122.  the import/export would be in the activate/deactivate event and suspend/resume
  123.  event routines.}
  124.  
  125. {$D+}
  126.  
  127. USES
  128.     MemTypes, QuickDraw, OSIntf, ToolIntf, PackIntf, Traps, AppleTalk, TransQueue;
  129.  
  130.  
  131. CONST
  132.     {MPW 3.0 will include a Traps.p interface file that includes constants for trap numbers.
  133.      These constants are from that file.}
  134.     {1.02 - Uses Traps.p to obtain trap numbers.}
  135.  
  136.     {1.01 - changed constants to begin with 'k' for consistency, except for resource IDs}
  137.     {kTextMargin is the number of pixels we leave blank at the edge of the window.}
  138.     kTextMargin                = 2;
  139.  
  140.     {kMaxOpenDocuments is used to determine whether a new document can be opened
  141.      or created. We keep track of the number of open documents, and disable the
  142.      menu items that create a new document when the maximum is reached. If the
  143.      number of documents falls below the maximum, the items are enabled again.}
  144.     kMaxOpenDocuments        = 1;
  145.     
  146.     {kMaxDocWidth is an arbitrary number used to specify the width of the TERec's
  147.     destination rectangle so that word wrap and horizontal scrolling can be
  148.     demonstrated.}
  149.     kMaxDocWidth            = 576;
  150.     
  151.     {kMinDocDim is used to limit the minimum dimension of a window when GrowWindow
  152.     is called.}
  153.     kMinDocDim                = 64;
  154.     
  155.     {kControlInvisible is used to 'turn off' controls (i.e., cause the control not
  156.     to be redrawn as a result of some Control Manager call such as SetCtlValue)
  157.     by being put into the contrlVis field of the record. kControlVisible is used
  158.     the same way to 'turn on' the control.}
  159.     kControlInvisible        = 0;
  160.     kControlVisible            = $FF;
  161.     
  162.     {kScrollBarAdjust and kScrollBarWidth are used in calculating
  163.     values for control positioning and sizing.}
  164.     kScrollbarWidth            = 16;
  165.     kScrollbarAdjust        = kScrollbarWidth - 1;
  166.     
  167.     {kScrollTweek compensates for off-by-one requirements of the scrollbars
  168.      to have borders coincide with the growbox.}
  169.     kScrollTweek            = 2;
  170.     
  171.     {kCrChar is used to match with a carriage return when calculating the
  172.     number of lines in the TextEdit record. kDelChar is used to check for
  173.     delete in keyDowns.}
  174.     kCRChar                    = 13;
  175.     kDelChar                = 8;
  176.     
  177.     {kButtonScroll is how many pixels to scroll horizontally when the button part
  178.     of the horizontal scrollbar is pressed.}
  179.     kButtonScroll            = 4;
  180.     
  181.     {kMaxTELength is an arbitrary number used to limit the length of text in the TERec
  182.     so that various errors won't occur from too many characters in the text.}
  183.     kMaxTELength            = 32000;
  184.  
  185.     {kSysEnvironsVersion is passed to SysEnvirons to tell it which version of the
  186.      SysEnvRec we understand.}
  187.     kSysEnvironsVersion        = 1;
  188.  
  189.     {kOSEvent is the event number of the suspend/resume and mouse-moved events sent
  190.      by MultiFinder. Once we determine that an event is an osEvent, we look at the
  191.      high byte of the message sent to determine which kind it is. To differentiate
  192.      suspend and resume events we check the resumeMask bit.}
  193.     kOSEvent                            = app4Evt;    {event used by MultiFinder}
  194.     kSuspendResumeMessage    = 1;        {high byte of suspend/resume event message}
  195.     kResumeMask                    = 1;        {bit of message field for resume vs. suspend}
  196.     kMouseMovedMessage        = $FA;    {high byte of mouse-moved event message}
  197.     kNoEvents                            = 0;        {no events mask}
  198.     
  199.     kReturnChar                        = 13;    {char code for the return character}
  200.  
  201.     {1.01 - kMinHeap - This is the minimum result from the following
  202.      equation:
  203.             
  204.             ORD(GetApplLimit) - ORD(ApplicZone)
  205.             
  206.      for the application to run. It will insure that enough memory will
  207.      be around for reasonable-sized scraps, FKEYs, etc. to exist with the
  208.      application, and still give the application some 'breathing room'.
  209.      To derive this number, we ran under a MultiFinder partition that was
  210.      our requested minimum size, as given in the 'SIZE' resource.}
  211.      
  212.     kMinHeap    = 29 * 1024;
  213.     
  214.     {1.01 - kMinSpace - This is the minimum result from PurgeSpace, when called
  215.      at initialization time, for the application to run. This number acts
  216.      as a double-check to insure that there really is enough memory for the
  217.      application to run, including what has been taken up already by
  218.      pre-loaded resources, the scrap, code, and other sundry memory blocks.}
  219.      
  220.     kMinSpace    = 20 * 1024;
  221.     
  222.     {kExtremeNeg and kExtremePos are used to set up wide open rectangles and regions.}
  223.     kExtremeNeg        = -32768;
  224.     kExtremePos        = 32767 - 1;    {required for old region bug}
  225.     
  226.     {kTESlop provides some extra security when pre-flighting edit commands.}
  227.     kTESlop            = 1024;
  228.  
  229.     {kErrStrings is the resource ID for the error strings STR# resource.}
  230.     kErrStrings        = 128;
  231.  
  232.     {The following are indicies into STR# resources.}
  233.     eWrongMachine    = 1;
  234.     eSmallSize        = 2;
  235.     eNoMemory        = 3;
  236.     eNoSpaceCut        = 4;
  237.     eNoCut                = 5;
  238.     eNoCopy            = 6;
  239.     eExceedPaste    = 7;
  240.     eNoSpacePaste    = 8;
  241.     eNoWindow        = 9;
  242.     eExceedChar        = 10;
  243.     eNoPaste            = 11;
  244.     eNoLAPMgr        = 12;
  245.     
  246.     {The following constants are all resource IDs, corresponding to resources in Sample.r.}
  247.     rMenuBar        = 128;                    {application's menu bar}
  248.     rAboutAlert    = 128;                    {about alert}
  249.     rUserAlert    = 129;                    {user error alert}
  250.     rDocWindow    = 128;                    {application's window}
  251.     rVScroll        = 128;                    {vertical scrollbar control}
  252.     rHScroll        = 129;                    {horizontal scrollbar control}
  253.  
  254.     {The following constants are used to identify menus and their items. The menu IDs
  255.      have an "m" prefix and the item numbers within each menu have an "i" prefix.}
  256.     mApple        = 128;                    {Apple menu}
  257.     iAbout        = 1;
  258.  
  259.     mFile        = 129;                    {File menu}
  260.     iNew            = 1;
  261.     iClose        = 4;
  262.     iQuit            = 12;
  263.  
  264.     mEdit        = 130;                    {Edit menu}
  265.     iUndo        = 1;
  266.     iCut            = 3;
  267.     iCopy        = 4;
  268.     iPaste        = 5;
  269.     iClear        = 6;
  270.     
  271.     mControl            = 131;                    {Control menu}
  272.     iNoMPPClose        = 1;
  273.     iNoNameChange = 2;
  274.     
  275.  
  276.     {1.01 - kDITop and kDILeft are used to locate the Disk Initialization dialogs.}
  277.     kDITop        = $0050;
  278.     kDILeft        = $0070;
  279.  
  280.  
  281. TYPE
  282.     {A DocumentRecord contains the WindowRecord for one of our document windows,
  283.      as well as the TEHandle for the text we are editing. We have added fields to
  284.      hold the ControlHandles to the vertical and horizontal scrollbars and to hold
  285.      the address of the default clikLoop that gets attached to a TERec when you call
  286.      TEAutoView. Other document fields can be added to this record as needed. For
  287.      a similar example, see how the Window Manager and Dialog Manager add fields
  288.      after the GrafPort.}
  289.     DocumentRecord    = RECORD
  290.         docWindow    : WindowRecord;
  291.         docTE            : TEHandle;
  292.         docVScroll    : ControlHandle;
  293.         docHScroll    : ControlHandle;
  294.         docClik            : ProcPtr;
  295.     END;
  296.     DocumentPeek    = ^DocumentRecord;
  297.  
  298.  
  299. VAR
  300.     {The "g" prefix is used to emphasize that a variable is global.}
  301.  
  302.     {GMac is used to hold the result of a SysEnvirons call. This makes
  303.      it convenient for any routine to check the environment. It is
  304.      global information, anyway.}
  305.     gMac                : SysEnvRec;    {set up by Initialize}
  306.  
  307.     {GHasWaitNextEvent is set at startup, and tells whether the WaitNextEvent
  308.      trap is available. If it is false, we know that we must call GetNextEvent.}
  309.     gHasWaitNextEvent    : BOOLEAN;        {set up by Initialize}
  310.  
  311.     {GInBackground is maintained by our OSEvent handling routines. Any part of
  312.      the program can check it to find out if it is currently in the background.}
  313.     gInBackground        : BOOLEAN;        {maintained by Initialize and DoEvent}
  314.  
  315.     {GNumDocuments is used to keep track of how many open documents there are
  316.      at any time. It is maintained by the routines that open and close documents.}
  317.     gNumDocuments        : INTEGER;        {maintained by Initialize, DoNew, and DoCloseWindow}
  318.     
  319.     {GATQEntry is used to set the pass the sample Transition Queue Handler to 
  320.      AppleTalk.}
  321.     gATQEntry            : myATQentry;
  322.     
  323. {$S Initialize}
  324. FUNCTION TrapAvailable(tNumber: INTEGER; tType: TrapType): BOOLEAN;
  325.  
  326. {Check to see if a given trap is implemented. This is only used by the
  327.  Initialize routine in this program, so we put it in the Initialize segment.
  328.  The recommended approach to see if a trap is implemented is to see if
  329.  the address of the trap routine is the same as the address of the
  330.  Unimplemented trap.}
  331. {1.02 - Needs to be called after call to SysEnvirons so that it can check
  332.  if a ToolTrap is out of range of a pre-MacII ROM.}
  333.  
  334. BEGIN
  335.     IF (tType = ToolTrap) &
  336.         (gMac.machineType > envMachUnknown) &
  337.         (gMac.machineType < envMacII) THEN BEGIN        {it's a 512KE, Plus, or SE}
  338.         tNumber := BAND(tNumber, $03FF);
  339.         IF tNumber > $01FF THEN                            {which means the tool traps}
  340.             tNumber := _Unimplemented;                    {only go to $01FF}
  341.     END;
  342.     TrapAvailable := NGetTrapAddress(tNumber, tType) <>
  343.                         GetTrapAddress(_Unimplemented);
  344. END; {TrapAvailable}
  345.  
  346.  
  347. {$S Main}
  348. FUNCTION IsDAWindow(window: WindowPtr): BOOLEAN;
  349.  
  350. {Check if a window belongs to a desk accessory.}
  351.  
  352. BEGIN
  353.     IF window = NIL THEN
  354.         IsDAWindow := FALSE
  355.     ELSE    {DA windows have negative windowKinds}
  356.         IsDAWindow := WindowPeek(window)^.windowKind < 0;
  357. END; {IsDAWindow}
  358.  
  359.  
  360. {$S Main}
  361. FUNCTION IsAppWindow(window: WindowPtr): BOOLEAN;
  362.  
  363. {Check to see if a window belongs to the application. If the window pointer
  364.  passed was NIL, then it could not be an application window. WindowKinds
  365.  that are negative belong to the system and windowKinds less than userKind
  366.  are reserved by Apple except for windowKinds equal to dialogKind, which
  367.  mean it is a dialog.
  368.  1.02 - In order to reduce the chance of accidentally treating some window
  369.  as an AppWindow that shouldn't be, we'll only return true if the windowkind
  370.  is userKind. If you add different kinds of windows to Sample you'll need
  371.  to change how this all works.}
  372.  
  373. BEGIN
  374.     IF window = NIL THEN
  375.         IsAppWindow := FALSE
  376.     ELSE    {application windows have windowKinds = userKind (8)}
  377.         WITH WindowPeek(window)^ DO
  378.             IsAppWindow := (windowKind = userKind);
  379. END; {IsAppWindow}
  380.  
  381.  
  382. {$S Main}
  383. PROCEDURE AlertUser(error: INTEGER);
  384.  
  385. {Display an alert that tells the user an error occurred, then exit the program.
  386.  This routine is used as an ultimate bail-out for serious errors that prohibit
  387.  the continuation of the application. Errors that do not require the termination
  388.  of the application should be handled in a different manner. Error checking and
  389.  reporting has a place even in the simplest application. The error number is used
  390.  to index an 'STR#' resource so that a relevant message can be displayed.}
  391.  
  392. VAR
  393.     itemHit    : INTEGER;
  394.     message    : Str255;
  395. BEGIN
  396.     SetCursor(arrow);
  397.     GetIndString(message, kErrStrings, error);
  398.     ParamText(message, '', '', '');
  399.     itemHit := Alert(rUserAlert, NIL);
  400. END; {AlertUser}
  401.  
  402.  
  403. {$S Main}
  404. PROCEDURE GetTERect(window: WindowPtr; VAR teRect: Rect);
  405.  
  406. {return a rectangle that is inset from the portRect by the size of
  407. the scrollbars and a little extra margin.}
  408.  
  409. BEGIN
  410.     teRect := window^.portRect;
  411.     InsetRect(teRect, kTextMargin, kTextMargin);            {adjust for margin}
  412.     teRect.bottom := teRect.bottom - kScrollbarAdjust;    {and for the scrollbars}
  413.     teRect.right := teRect.right - kScrollbarAdjust;
  414. END; {GetTERect}
  415.  
  416.  
  417. {$S Main}
  418. FUNCTION DoCloseWindow(window: WindowPtr) : BOOLEAN;
  419.  
  420. {Close a window. This handles desk accessory and application windows.}
  421.  
  422. {1.01 - At this point, if there was a document associated with a
  423.  window, you could do any document saving processing if it is 'dirty'.
  424.  DoCloseWindow would return TRUE if the window actually closed, i.e.,
  425.  the user didn’t cancel from a save dialog. This result is handy when
  426.  the user quits an application, but then cancels the save of a document
  427.  associated with a window.}
  428.  
  429. BEGIN
  430.     DoCloseWindow := TRUE;
  431.     IF IsDAWindow(window) THEN
  432.         CloseDeskAcc(WindowPeek(window)^.windowKind)
  433.     ELSE IF IsAppWindow(window) THEN BEGIN
  434.         WITH DocumentPeek(window)^ DO
  435.             IF docTE <> NIL THEN BEGIN
  436.                 TEDispose(docTE);        {dispose the TEHandle}
  437.                 if  (gATQEntry.globs^.docTE <> nil) THEN
  438.                     gATQEntry.globs^.docTE := NIL;
  439.             END;
  440.         {1.01 - We used to call DisposeWindow, but that was technically
  441.          incorrect, even though we allocated storage for the window on
  442.          the heap. We should instead call CloseWindow to have the structures
  443.          taken care of and then dispose of the storage ourselves.}
  444.         CloseWindow(window);
  445.         DisposPtr(Ptr(window));
  446.         gNumDocuments := gNumDocuments - 1;
  447.     END;
  448. END; {DoCloseWindow}
  449.  
  450.  
  451. {$S Main}
  452. PROCEDURE AdjustViewRect(docTE: TEHandle);
  453.  
  454. {Update the TERec's view rect so that it is the greatest multiple of
  455. the lineHeight and still fits in the old viewRect.}
  456.  
  457. BEGIN
  458.     WITH docTE^^ DO BEGIN
  459.         viewRect.bottom := (((viewRect.bottom - viewRect.top) DIV lineHeight) *
  460.                             lineHeight) + viewRect.top;
  461.     END;
  462. END; {AdjustViewRect}
  463.  
  464.  
  465. {$S Main}
  466. PROCEDURE AdjustTE(window: WindowPtr);
  467.  
  468. {Scroll the TERec around to match up to the potentially updated scrollbar
  469. values. This is really useful when the window resizes such that the
  470. scrollbars become inactive and the TERec had been previously scrolled.}
  471.  
  472. VAR
  473.     value    : INTEGER;
  474. BEGIN
  475.     WITH DocumentPeek(window)^ DO BEGIN
  476.         TEScroll((docTE^^.viewRect.left - docTE^^.destRect.left) - GetCtlValue(docHScroll),
  477.                 (docTE^^.viewRect.top - docTE^^.destRect.top) -
  478.                     (GetCtlValue(docVScroll) * docTE^^.lineHeight),
  479.                 docTE);
  480.     END;
  481. END; {AdjustTE}
  482.  
  483.  
  484. {$S Main}
  485. PROCEDURE AdjustHV(isVert: BOOLEAN; control: ControlHandle; docTE: TEHandle; canRedraw: BOOLEAN);
  486.  
  487. {Calculate the new control maximum value and current value, whether it is the horizontal or
  488. vertical scrollbar. The vertical max is calculated by comparing the number of lines to the
  489. vertical size of the viewRect. The horizontal max is calculated by comparing the maximum document
  490. width to the width of the viewRect. The current values are set by comparing the offset between
  491. the view and destination rects. If necessary and we canRedraw, have the control be re-drawn by
  492. calling ShowControl.}
  493.  
  494. VAR
  495.     value, lines, max    : INTEGER;
  496.     oldValue, oldMax    : INTEGER;
  497. BEGIN
  498.     oldValue := GetCtlValue(control);
  499.     oldMax := GetCtlMax(control);
  500.     IF isVert THEN BEGIN
  501.         lines := docTE^^.nLines;
  502.         {since nLines isn’t right if the last character is a return, check for that case}
  503.         IF Ptr(ORD(docTE^^.hText^) + docTE^^.teLength - 1)^ = kCRChar THEN
  504.             lines := lines + 1;
  505.         max := lines - ((docTE^^.viewRect.bottom - docTE^^.viewRect.top) DIV docTE^^.lineHeight);
  506.     END ELSE
  507.         max := kMaxDocWidth - (docTE^^.viewRect.right - docTE^^.viewRect.left);
  508.     IF max < 0 THEN max := 0;            {check for negative values}
  509.     SetCtlMax(control, max);
  510.     IF isVert THEN
  511.         value := (docTE^^.viewRect.top - docTE^^.destRect.top) DIV docTE^^.lineHeight
  512.     ELSE
  513.         value := docTE^^.viewRect.left - docTE^^.destRect.left;
  514.     IF value < 0 THEN
  515.         value := 0
  516.     ELSE IF value > max THEN
  517.         value := max;                    {pin the value to within range}
  518.     SetCtlValue(control, value);
  519.     IF canRedraw & ( (max <> oldMax) | (value <> oldValue) ) THEN
  520.         ShowControl(control);            {check to see if the control can be re-drawn}
  521. END; {AdjustHV}
  522.  
  523.  
  524. {$S Main}
  525. PROCEDURE AdjustScrollValues(window: WindowPtr; canRedraw: BOOLEAN);
  526.  
  527. {Simply call the common adjust routine for the vertical and horizontal scrollbars.}
  528.  
  529. BEGIN
  530.     WITH DocumentPeek(window)^ DO BEGIN
  531.         AdjustHV(TRUE, docVScroll, docTE, canRedraw);
  532.         AdjustHV(FALSE, docHScroll, docTE, canRedraw);
  533.     END;
  534. END; {AdjustScrollValues}
  535.  
  536.  
  537. {$S Main}
  538. PROCEDURE AdjustScrollSizes(window: WindowPtr);
  539.  
  540. {Re-calculate the position and size of the viewRect and the scrollbars.
  541.  kScrollTweek compensates for off-by-one requirements of the scrollbars
  542.  to have borders coincide with the growbox.}
  543.  
  544. VAR
  545.     teRect    : Rect;
  546. BEGIN
  547.     GetTERect(window, teRect);                                        {start with teRect}
  548.     WITH DocumentPeek(window)^, window^.portRect DO BEGIN
  549.         docTE^^.viewRect := teRect;
  550.         AdjustViewRect(docTE);                                        {snap to nearest line}
  551.         MoveControl(docVScroll, right - kScrollbarAdjust, -1);
  552.         SizeControl(docVScroll, kScrollbarWidth, (bottom - top) -
  553.                         (kScrollbarAdjust - kScrollTweek));
  554.         MoveControl(docHScroll, -1, bottom - kScrollbarAdjust);
  555.         SizeControl(docHScroll, (right - left) - (kScrollbarAdjust -
  556.                         kScrollTweek), kScrollbarWidth);
  557.     END;
  558. END; {AdjustScrollSizes}
  559.  
  560.  
  561. {$S Main}
  562. PROCEDURE AdjustScrollbars(window: WindowPtr; needsResize: BOOLEAN);
  563.  
  564. {Turn off the controls by jamming a zero into their contrlVis fields (HideControl erases them
  565. and we don't want that). If the controls are to be resized as well, call the procedure to do that,
  566. then call the procedure to adjust the maximum and current values. Finally re-enable the controls
  567. by jamming a $FF in their contrlVis fields.}
  568.  
  569. VAR
  570.     oldMax, oldVal    : INTEGER;
  571. BEGIN
  572.     WITH DocumentPeek(window)^ DO BEGIN
  573.         {First, turn visibility of scrollbars off so we won’t get unwanted redrawing}
  574.         docVScroll^^.contrlVis := kControlInvisible;    {turn them off}
  575.         docHScroll^^.contrlVis := kControlInvisible;
  576.         IF needsResize THEN                                {move and size if needed}
  577.             AdjustScrollSizes(window);
  578.         AdjustScrollValues(window, NOT needsResize);    {fool with max and current value}
  579.         {Now, restore visibility in case we never had to ShowControl during adjustment}
  580.         docVScroll^^.contrlVis := kControlVisible;        {turn them on}
  581.         docHScroll^^.contrlVis := kControlVisible;
  582.     END;
  583. END; {AdjustScrollbars}
  584.  
  585.  
  586. {$S Main}
  587. {$PUSH} {$Z+}
  588. PROCEDURE PascalClikLoop;
  589.  
  590. {Gets called from our assembly language routine, AsmClikLoop, which is in
  591.  turn called by the TEClick toolbox routine. Saves the windows clip region,
  592.  sets it to the portRect, adjusts the scrollbar values to match the TE scroll
  593.  amount, then restores the clip region.}
  594.  
  595. VAR
  596.     window    : WindowPtr;
  597.     region    : RgnHandle;
  598. BEGIN
  599.     window := FrontWindow;
  600.     region := NewRgn;
  601.     GetClip(region);                    {save the old clip}
  602.     ClipRect(window^.portRect);            {set the new clip}
  603.     AdjustScrollValues(window, TRUE);    {pass TRUE for canRedraw}
  604.     SetClip(region);                    {restore the old clip}
  605.     DisposeRgn(region);
  606. END; {PascalClikLoop}
  607. {$POP}
  608.  
  609.  
  610. {$S Main}
  611. {$PUSH} {$Z+}
  612. FUNCTION GetOldClikLoop : ProcPtr;
  613.  
  614. {Gets called from our assembly language routine, AsmClikLoop, which is in
  615. turn called by the TEClick toolbox routine. It returns the address of the
  616. default clikLoop routine that was put into the TERec by TEAutoView to
  617. AsmClikLoop so that it can call it.}
  618.  
  619. BEGIN
  620.     GetOldClikLoop := DocumentPeek(FrontWindow)^.docClik;
  621. END; {GetOldClikLoop}
  622. {$POP}
  623.  
  624.  
  625. PROCEDURE AsmClikLoop; EXTERNAL;
  626.  
  627. {A reference to our assembly language routine that gets attached to the clikLoop
  628. field of our TE record.}
  629.  
  630.  
  631. {$S Main}
  632. PROCEDURE DoNew;
  633.  
  634. {Create a new document and window.}
  635.  
  636. VAR
  637.     good, ignore        : BOOLEAN;
  638.     storage                : Ptr;
  639.     window                : WindowPtr;
  640.     destRect, viewRect    : Rect;
  641.  
  642. BEGIN
  643.     storage := NewPtr(SIZEOF(DocumentRecord));
  644.     IF storage <> NIL THEN BEGIN
  645.         window := GetNewWindow(rDocWindow, storage, WindowPtr(-1));
  646.         IF window <> NIL THEN BEGIN
  647.             gNumDocuments := gNumDocuments + 1;    {this will be decremented when we call DoCloseWindow}
  648.             good := FALSE;
  649.             SetPort(window);
  650.             WITH window^, DocumentPeek(window)^ DO BEGIN
  651.                 GetTERect(window, viewRect);
  652.                 destRect := viewRect;
  653.                 destRect.right := destRect.left + kMaxDocWidth;
  654.                 docTE := TENew(destRect, viewRect);
  655.                 IF docTE <> NIL THEN BEGIN        {1.02 - moved}
  656.                     good := TRUE;                {if TENew succeeded, we have a good document}
  657.                     AdjustViewRect(docTE);
  658.                     TEAutoView(TRUE, docTE);
  659.                     docClik := docTE^^.clikLoop;
  660.                     docTE^^.clikLoop := @AsmClikLoop;
  661.                     if (gATQEntry.globs^.docTE = nil ) THEN
  662.                         gATQEntry.globs^.docTE := docTE;    {store TEHandle in the ATQ Globals record }
  663.                 END;
  664.                 IF good THEN BEGIN
  665.                     docVScroll := GetNewControl(rVScroll, window);
  666.                     good := (docVScroll <> NIL);
  667.                 END;
  668.                 IF good THEN BEGIN
  669.                     docHScroll := GetNewControl(rHScroll, window);
  670.                     good := (docHScroll <> NIL);
  671.                 END;
  672.                 IF good THEN BEGIN
  673.                     {FALSE to AdjustScrollValues means musn’t redraw; technically, of course,
  674.                     the window is hidden so it wouldn’t matter whether we called ShowControl or not.}
  675.                     AdjustScrollValues(window, FALSE);
  676.                     ShowWindow(window);            {if the document is good, make the window visible}
  677.                 END ELSE BEGIN
  678.                     ignore := DoCloseWindow(window);    {otherwise regret we ever created it...}
  679.                     AlertUser(eNoWindow);                {and tell user}
  680.                 END
  681.             END;
  682.         END ELSE
  683.             DisposPtr(storage);                    {get rid of the storage if it is never used}
  684.     END;
  685. END; {DoNew}
  686.  
  687.  
  688. {$S Main}
  689. PROCEDURE BigBadError(error: INTEGER);
  690. BEGIN
  691.     AlertUser(error);
  692.     ExitToShell;
  693. END;
  694.  
  695. PROCEDURE CallTransQueue; EXTERNAL;
  696.  
  697. {$S Initialize}
  698. PROCEDURE Initialize;
  699.  
  700. {Set up the whole world, including global variables, Toolbox managers,
  701.  menus, and a single blank document.}
  702.  
  703. {1.01 - The code that used to be part of ForceEnvirons has been moved into
  704.  this module. If an error is detected, instead of merely doing an ExitToShell,
  705.  which leaves the user without much to go on, we call AlertUser, which puts
  706.  up a simple alert that just says an error occurred and then calls ExitToShell.
  707.  Since there is no other cleanup needed at this point if an error is detected,
  708.  this form of error- handling is acceptable. If more sophisticated error recovery
  709.  is needed, an exception mechanism, such as is provided by Signals, can be used.}
  710.  
  711. VAR
  712.     menuBar                : Handle;
  713.     total, contig        : LongInt;
  714.     ignoreResult        : BOOLEAN;
  715.     event                : EventRecord;
  716.     count, ignoreError    : INTEGER;
  717.     err                    : OSErr;
  718.     
  719.     PROCEDURE BigBadError(error: INTEGER);
  720.     BEGIN
  721.         AlertUser(error);
  722.         ExitToShell;
  723.     END;
  724.  
  725. BEGIN
  726.     gInBackground := FALSE;
  727.  
  728.     InitGraf(@thePort);
  729.     InitFonts;
  730.     InitWindows;
  731.     InitMenus;
  732.     TEInit;
  733.     InitDialogs(NIL);
  734.     InitCursor;
  735.     
  736.     {This next bit of code is necessary to allow the default button of our
  737.      alert be outlined.
  738.      1.02 - Changed to call EventAvail so that we don't lose some important
  739.      events.}
  740.      
  741.     FOR count := 1 TO 3 DO
  742.         ignoreResult := EventAvail(everyEvent, event);
  743.     
  744.     {Ignore the error returned from SysEnvirons; even if an error occurred,
  745.      the SysEnvirons glue will fill in the SysEnvRec. You can save a redundant
  746.      call to SysEnvirons by calling it after initializing AppleTalk.}
  747.      
  748.     ignoreError := SysEnvirons(kSysEnvironsVersion, gMac);
  749.     
  750.     {Make sure that the machine has at least 128K ROMs. If it doesn't, exit.}
  751.     
  752.     IF gMac.machineType < 0 THEN BigBadError(eWrongMachine);
  753.     
  754.     {1.02 - Move TrapAvailable call to after SysEnvirons so that we can tell
  755.      in TrapAvailable if a tool trap value is out of range.}
  756.      
  757.     gHasWaitNextEvent := TrapAvailable(_WaitNextEvent, ToolTrap);
  758.  
  759.     {1.01 - We used to make a check for memory at this point by examining ApplLimit,
  760.      ApplicZone, and StackSpace and comparing that to the minimum size we told
  761.      MultiFinder we needed. This did not work well because it assumed too much about
  762.      the relationship between what we asked MultiFinder for and what we would actually
  763.      get back, as well as how to measure it. Instead, we will use an alternate
  764.      method comprised of two steps.}
  765.      
  766.     {It is better to first check the size of the application heap against a value
  767.      that you have determined is the smallest heap the application can reasonably
  768.      work in. This number should be derived by examining the size of the heap that
  769.      is actually provided by MultiFinder when the minimum size requested is used.
  770.      The derivation of the minimum size requested from MultiFinder is described
  771.      in Sample.h. The check should be made because the preferred size can end up
  772.      being set smaller than the minimum size by the user. This extra check acts to
  773.      insure that your application is starting from a solid memory foundation.}
  774.      
  775.     IF ORD(GetApplLimit) - ORD(ApplicZone) < kMinHeap THEN BigBadError(eSmallSize);
  776.     
  777.     {Next, make sure that enough memory is free for your application to run. It
  778.      is possible for a situation to arise where the heap may have been of required
  779.      size, but a large scrap was loaded which left too little memory. To check for
  780.      this, call PurgeSpace and compare the result with a value that you have determined
  781.      is the minimum amount of free memory your application needs at initialization.
  782.      This number can be derived several different ways. One way that is fairly
  783.      straightforward is to run the application in the minimum size configuration
  784.      as described previously. Call PurgeSpace at initialization and examine the value
  785.      returned. However, you should make sure that this result is not being modified
  786.      by the scrap's presence. You can do that by calling ZeroScrap before calling
  787.      PurgeSpace. Make sure to remove that call before shipping, though.}
  788.      
  789.     {* ZeroScrap; *}
  790.     PurgeSpace(total, contig);
  791.     IF total < kMinSpace THEN
  792.         IF UnloadScrap <> noErr THEN
  793.             BigBadError(eNoMemory)
  794.         ELSE BEGIN
  795.             PurgeSpace(total, contig);
  796.             IF total < kMinSpace THEN
  797.                 BigBadError(eNoMemory);
  798.         END;
  799.  
  800.     {The extra benefit to waiting until after the Toolbox Managers have been initialized
  801.      to check memory is that we can now give the user an alert to tell her/him what
  802.      happened. Although it is possible that the memory situation could be worsened by
  803.      displaying an alert, MultiFinder would gracefully exit the application with
  804.      an informative alert if memory became critical. Here we are acting more
  805.      in a preventative manner to avoid future disaster from low-memory problems.}
  806.  
  807.     menuBar := GetNewMBar(rMenuBar);        {read menus into menu bar}
  808.     IF menuBar = NIL THEN
  809.         BigBadError(eNoMemory);
  810.     SetMenuBar(menuBar);                    {install menus}
  811.     DisposHandle(menuBar);
  812.     AddResMenu(GetMHandle(mApple), 'DRVR');    {add DA names to Apple menu}
  813.     DrawMenuBar;
  814.  
  815.     gNumDocuments := 0;
  816.  
  817.     err := InitTransEventRec(gATQEntry.globs); { initialize the TransEventRec }
  818.     if (err <> noErr) THEN
  819.         BigBadError(eNoMemory);
  820.     gATQEntry.CallAddr := ProcPtr(@CallTransQueue);
  821.     err := LAPAddATQ(ATQEntryPtr(@gATQEntry));  { add our handler to the Trans Queue }
  822.     if (err <> noErr) THEN
  823.         BigBadError(eNoLAPMgr);        { Cannot install ATQ handler }
  824.  
  825.     DoNew;                                    {create a single empty document}
  826. END; {Initialize}
  827.  
  828.  
  829. (**************************************************************************************
  830. 1.01 - PROCEDURE DoCloseBehind(window: WindowPtr); was removed.
  831.  
  832. {1.01 - DoCloseBehind was a good idea for closing windows when quitting
  833.  and not having to worry about updating the windows, but it suffered
  834.  from a fatal flaw. If a desk accessory owned two windows, it would
  835.  close both those windows when CloseDeskAcc was called. When DoCloseBehind
  836.  got around to calling DoCloseWindow for that other window that was already
  837.  closed, things would go very poorly. Another option would be to have a
  838.  procedure, GetRearWindow, that would go through the window list and return
  839.  the last window. Instead, we decided to present the standard approach
  840.  of getting and closing FrontWindow until FrontWindow returns NIL. This
  841.  has a potential benefit in that the window whose document needs to be saved
  842.  may be visible since it is the front window, therefore decreasing the
  843.  chance of user confusion. For aesthetic reasons, the windows in the
  844.  application should be checked for updates periodically and have the
  845.  updates serviced.}
  846. **************************************************************************************)
  847.  
  848.  
  849. {$S Main}
  850. PROCEDURE Terminate;
  851.  
  852. {Clean up the application and exit. We close all of the windows so that
  853.  they can update their documents, if any.}
  854.  
  855. {1.01 - If we find out that a cancel has occurred, we won't exit to the
  856.  shell, but will return instead.}
  857.  
  858. VAR
  859.     aWindow    : WindowPtr;
  860.     closed    : BOOLEAN;
  861.     err        : OSErr;
  862.  
  863. BEGIN
  864.     closed := TRUE;
  865.     REPEAT
  866.         aWindow := FrontWindow;                    {get the current front window}
  867.         IF aWindow <> NIL THEN
  868.             closed := DoCloseWindow(aWindow);    {close this window}
  869.     UNTIL (NOT closed) | (aWindow = NIL);        {do all windows}
  870.     err := LAPRmvATQ(ATQEntryPtr(@gATQEntry));
  871.     IF closed THEN
  872.         ExitToShell;                            {exit if no cancellation}
  873. END; {Terminate}
  874.  
  875.  
  876. {$S Main}
  877. PROCEDURE AdjustMenus;
  878.  
  879. {Enable and disable menus based on the current state.
  880.  The user can only select enabled menu items. We set up all the menu items
  881.  before calling MenuSelect or MenuKey, since these are the only times that
  882.  a menu item can be selected. Note that MenuSelect is also the only time
  883.  the user will see menu items. This approach to deciding what enable/
  884.  disable state a menu item has the advantage of concentrating all the decision-
  885.  making in one routine, as opposed to being spread throughout the application.
  886.  Other application designs may take a different approach that may or may not be
  887.  as valid.}
  888.  
  889. VAR
  890.     window            : WindowPtr;
  891.     menu            : MenuHandle;
  892.     offset            : LONGINT;
  893.     undo            : BOOLEAN;
  894.     cutCopyClear    : BOOLEAN;
  895.     paste            : BOOLEAN;
  896.  
  897. BEGIN
  898.     window := FrontWindow;
  899.  
  900.     menu := GetMHandle(mFile);
  901.     IF gNumDocuments < kMaxOpenDocuments THEN
  902.         EnableItem(menu, iNew)        {New is enabled when we can open more documents}
  903.     ELSE
  904.         DisableItem(menu, iNew);
  905.     IF window <> NIL THEN            {Close is enabled when there is a window to close}
  906.         EnableItem(menu, iClose)
  907.     ELSE
  908.         DisableItem(menu, iClose);
  909.  
  910.     menu := GetMHandle(mEdit);
  911.     undo := FALSE;
  912.     cutCopyClear := FALSE;
  913.     paste := FALSE;
  914.     IF IsDAWindow(window) THEN BEGIN
  915.         undo := TRUE;                {all editing is enabled for DA windows}
  916.         cutCopyClear := TRUE;
  917.         paste := TRUE;
  918.     END ELSE IF IsAppWindow(window) THEN BEGIN
  919.         WITH DocumentPeek(window)^.docTE^^ DO
  920.             IF selStart < selEnd THEN
  921.                 cutCopyClear := TRUE;
  922.                 {Cut, Copy, and Clear is enabled for app. windows with selections}
  923.         IF GetScrap(NIL, 'TEXT', offset) > 0 THEN
  924.             paste := TRUE;            {Paste is enabled for app. windows}
  925.     END;
  926.     IF undo THEN
  927.         EnableItem(menu, iUndo)
  928.     ELSE
  929.         DisableItem(menu, iUndo);
  930.     IF cutCopyClear THEN BEGIN
  931.         EnableItem(menu, iCut);
  932.         EnableItem(menu, iCopy);
  933.         EnableItem(menu, iClear);
  934.     END ELSE BEGIN
  935.         DisableItem(menu, iCut);
  936.         DisableItem(menu, iCopy);
  937.         DisableItem(menu, iClear);
  938.     END;
  939.     IF paste THEN
  940.         EnableItem(menu, iPaste)
  941.     ELSE
  942.         DisableItem(menu, iPaste);
  943. END; {AdjustMenus}
  944.  
  945.  
  946. {$S Main}
  947. PROCEDURE DoMenuCommand(menuResult: LONGINT);
  948.  
  949. {This is called when an item is chosen from the menu bar (after calling
  950.  MenuSelect or MenuKey). It does the right thing for each command.}
  951.  
  952. VAR
  953.     menuID, menuItem        : INTEGER;
  954.     itemHit, daRefNum        : INTEGER;
  955.     daName                    : Str255;
  956.     ignoreResult, saveErr    : OSErr;
  957.     handledByDA                : BOOLEAN;
  958.     te                        : TEHandle;
  959.     window                    : WindowPtr;
  960.     ignore                    : BOOLEAN;
  961.     aHandle                    : Handle;
  962.     oldSize, newSize        : LongInt;
  963.     total, contig            : LongInt;
  964.  
  965. BEGIN
  966.     window := FrontWindow;
  967.     menuID := HiWrd(menuResult);    {use built-ins (for efficiency)...}
  968.     menuItem := LoWrd(menuResult);    {to get menu item number and menu number}
  969.     CASE menuID OF
  970.     
  971.         mApple:
  972.             CASE menuItem OF
  973.                 iAbout:                {bring up alert for About}
  974.                     itemHit := Alert(rAboutAlert, NIL);
  975.                 OTHERWISE BEGIN        {all non-About items in this menu are DAs}
  976.                     GetItem(GetMHandle(mApple), menuItem, daName);
  977.                     daRefNum := OpenDeskAcc(daName);
  978.                 END;
  979.             END;
  980.             
  981.         mFile:
  982.             CASE menuItem OF
  983.                 iNew:
  984.                     DoNew;
  985.                 iClose:
  986.                     ignore := DoCloseWindow(window); {we don't care if cancelled}
  987.                 iQuit:
  988.                     Terminate;
  989.             END;
  990.             
  991.         mEdit: BEGIN                {call SystemEdit for DA editing & MultiFinder}
  992.             IF (SystemEdit(menuItem-1)) THEN BEGIN
  993.             END;
  994.         END;
  995.         
  996.         mControl:
  997.             CASE menuItem OF
  998.                 iNoMPPClose: BEGIN            { toggle MPPClose selection flag to allow/prohibit .MPP closure }
  999.                     IF (gATQEntry.globs^.allowClose) THEN BEGIN
  1000.                         gATQEntry.globs^.allowClose := FALSE;
  1001.                         SetItem(GetMHandle(mControl), iNoMPPClose, 'Allow .MPP Closure');
  1002.                     END
  1003.                     ELSE BEGIN
  1004.                         gATQEntry.globs^.allowClose := TRUE;
  1005.                         SetItem(GetMHandle(mControl), iNoMPPClose, 'Prohibit .MPP Closure');
  1006.                     END
  1007.                 END;
  1008.                 
  1009.                 iNoNameChange: BEGIN            { toggle Flagship Name change flag to allow/prohibit name change } 
  1010.                     IF (gATQEntry.globs^.allowChange) THEN BEGIN
  1011.                         gATQEntry.globs^.allowChange := FALSE;
  1012.                         SetItem(GetMHandle(mControl), iNoNameChange, 'Allow Name Change');
  1013.                     END
  1014.                     ELSE BEGIN
  1015.                         gATQEntry.globs^.allowChange := TRUE;
  1016.                         SetItem(GetMHandle(mControl), iNoNameChange, 'Prohibit Name Change');
  1017.                     END
  1018.                 END;
  1019.             END; { CASE menuItem of }
  1020.         
  1021.     END;    { CASE menuID OF }
  1022.     HiliteMenu(0);                    {unhighlight what MenuSelect (or MenuKey) hilited}
  1023. END; {DoMenuCommand}
  1024.  
  1025.  
  1026. {$S Main}
  1027. PROCEDURE DrawWindow(window: WindowPtr);
  1028.  
  1029. {Draw the contents of an application window.}
  1030.  
  1031. BEGIN
  1032.     SetPort(window);
  1033.     WITH window^ DO BEGIN
  1034.         EraseRect(portRect);        {as per TextEdit chapter of Inside Macintosh}
  1035.         DrawControls(window);        {this ordering makes for a better appearance}
  1036.         DrawGrowIcon(window);
  1037.         TEUpdate(portRect, DocumentPeek(window)^.docTE);
  1038.     END;
  1039. END; {DrawWindow}
  1040.  
  1041.  
  1042. {$S Main}
  1043. FUNCTION GetSleep: LONGINT;
  1044.  
  1045. {Calculate a sleep value for WaitNextEvent. This takes into account the things
  1046.  that DoIdle does with idle time.}
  1047.  
  1048. VAR
  1049.     sleep    : LONGINT;
  1050.     window    : WindowPtr;
  1051.  
  1052. BEGIN
  1053.     sleep := 60;                    {default value for sleep}
  1054.     IF NOT gInBackground THEN BEGIN            {if we are in front...}
  1055.         window := FrontWindow;            {and the front window is ours...}
  1056.         IF IsAppWindow(window) THEN BEGIN
  1057.             WITH DocumentPeek(window)^.docTE^^ DO
  1058.                 IF selStart = selEnd THEN    {and the selection is an insertion point...}
  1059.                     sleep := GetCaretTime;    {we need to blink the insertion point}
  1060.         END;
  1061.     END;
  1062.     GetSleep := sleep;
  1063. END; {GetSleep}
  1064.  
  1065.  
  1066. {$S Main}
  1067. PROCEDURE CommonAction(control: ControlHandle; VAR amount: INTEGER);
  1068.  
  1069. {Common algorithm for setting the new value of a control. It returns the actual amount
  1070. the value of the control changed. Note the pinning is done for the sake of returning
  1071. the amount the control value changed.}
  1072.  
  1073. VAR
  1074.     value, max    : INTEGER;
  1075.     window        : WindowPtr;
  1076. BEGIN
  1077.     value := GetCtlValue(control);    {get current value}
  1078.     max := GetCtlMax(control);        {and max value}
  1079.     amount := value - amount;
  1080.     IF amount < 0 THEN
  1081.         amount := 0
  1082.     ELSE IF amount > max THEN
  1083.         amount := max;
  1084.     SetCtlValue(control, amount);
  1085.     amount := value - amount;        {calculate true change}
  1086. END; {CommonAction}
  1087.  
  1088.  
  1089. {$S Main}
  1090. PROCEDURE VActionProc(control: ControlHandle; part: INTEGER);
  1091.  
  1092. {Determines how much to change the value of the vertical scrollbar by and how
  1093. much to scroll the TE record.}
  1094.  
  1095. VAR
  1096.     amount    : INTEGER;
  1097.     window    : WindowPtr;
  1098. BEGIN
  1099.     IF part <> 0 THEN BEGIN
  1100.         window := control^^.contrlOwner;
  1101.         WITH DocumentPeek(window)^, DocumentPeek(window)^.docTE^^ DO BEGIN
  1102.             CASE part OF
  1103.                 inUpButton, inDownButton:
  1104.                     amount := 1;                                                {one line}
  1105.                 inPageUp, inPageDown:
  1106.                     amount := (viewRect.bottom - viewRect.top) DIV lineHeight;    {one page}
  1107.             END;
  1108.             IF (part = inDownButton) | (part = inPageDown) THEN
  1109.                 amount := -amount;                                                {reverse direction}
  1110.             CommonAction(control, amount);
  1111.             IF amount <> 0 THEN
  1112.                 TEScroll(0, amount * docTE^^.lineHeight, docTE);
  1113.         END;
  1114.     END;
  1115. END; {VActionProc}
  1116.  
  1117.  
  1118. {$S Main}
  1119. PROCEDURE HActionProc(control: ControlHandle; part: INTEGER);
  1120.  
  1121. {Determines how much to change the value of the horizontal scrollbar by and how
  1122. much to scroll the TE record.}
  1123.  
  1124. VAR
  1125.     amount    : INTEGER;
  1126.     window    : WindowPtr;
  1127. BEGIN
  1128.     IF part <> 0 THEN BEGIN
  1129.         window := control^^.contrlOwner;
  1130.         WITH DocumentPeek(window)^, DocumentPeek(window)^.docTE^^ DO BEGIN
  1131.             CASE part OF
  1132.                 inUpButton, inDownButton:                                        {a few pixels}
  1133.                     amount := kButtonScroll;
  1134.                 inPageUp, inPageDown:
  1135.                     amount := viewRect.right - viewRect.left;                    {a page}
  1136.             END;
  1137.             IF (part = inDownButton) | (part = inPageDown) THEN
  1138.                 amount := -amount;                                                {reverse direction}
  1139.             CommonAction(control, amount);
  1140.             IF amount <> 0 THEN
  1141.                 TEScroll(amount, 0, docTE);
  1142.         END;
  1143.     END;
  1144. END; {HActionProc}
  1145.  
  1146.  
  1147. {$S Main}
  1148. PROCEDURE DoIdle;
  1149.  
  1150. {This is called whenever we get an null event or a mouse-moved event.
  1151.  It takes care of necessary periodic actions. For this program, it calls TEIdle.}
  1152.  
  1153. VAR
  1154.     window    : WindowPtr;
  1155.     myGRec: TransEventPtr;
  1156.     te            : TEHandle;
  1157.     strHdl1    : StringHandle;
  1158.     strHdl2    : StringHandle;
  1159.     strHdl3    : StringHandle;
  1160.     err        : OSErr;
  1161.     dtRec    : DateTimeRec;
  1162.     dtStr    : Str32;
  1163.     netStr    : Str255;
  1164.     i            : INTEGER;    { used to index into indEvtRec }
  1165.     
  1166.     FUNCTION GetMyStrings(evtNum : INTEGER; VAR s1, s2, s3 : StringHandle) : OSErr;
  1167.     
  1168.     BEGIN
  1169.         s1 := StringHandle(GetResource('STR ', evtNum));
  1170.         s2 := nil;
  1171.         s3 := nil;
  1172.         if (s1 <> NIL) THEN BEGIN
  1173.             CASE evtNum of
  1174.                 kATTransNameChangeTellTaskMsgNum,
  1175.                 kATTransNameChangeAskTaskMsgNum :
  1176.                     s2 := StringHandle(GetResource('STR ', kNewFlagshipNameMsg));
  1177.                 kATTransCancelNameChangeMsgNum :
  1178.                     s2 := StringHandle(GetResource('STR ', kCancelFlagshipNameMsg));
  1179.                 kATTransCableChangeMsgNum : BEGIN
  1180.                     s2 := StringHandle(GetResource('STR ', kLoCableRangeMsg));
  1181.                     s3 := StringHandle(GetResource('STR ', kHiCableRangeMsg));
  1182.                 END;
  1183.                 kATTransNetworkTransitionMsgNum : BEGIN
  1184.                     IF (gATQEntry.globs^.newConnFlag) THEN
  1185.                         s2 := StringHandle(GetResource('STR ', kNewConnection))
  1186.                     ELSE
  1187.                         s2 := StringHandle(GetResource('STR ', kCloseConnection));
  1188.                 END;
  1189.             END;
  1190.         END;
  1191.         GetMyStrings := ResError;
  1192.     END;
  1193.     
  1194.     FUNCTION DateRecToStr(dtRec : DateTimeRec) : Str255;
  1195.     
  1196.     VAR
  1197.         yearStr    : Str255;
  1198.         monthStr    : Str255;
  1199.         dayStr    : Str255;
  1200.         hourStr    : Str255;
  1201.         minStr    : Str255;
  1202.         secStr    : Str255;
  1203.         
  1204.     BEGIN
  1205.         NumToString(dtRec.year, yearStr);
  1206.         NumToString(dtRec.month, monthStr);
  1207.         NumToString(dtRec.day, dayStr);
  1208.         NumToString(dtRec.hour, hourStr);
  1209.         NumToString(dtRec.minute, minStr);
  1210.         NumToString(dtRec.second, secStr);
  1211.         dtStr := Concat(monthStr, '/', dayStr, '/', yearStr, '   ', hourStr, ':', minStr, ':', secStr);
  1212.         DateRecToStr := dtStr;
  1213.     END;
  1214.  
  1215.     PROCEDURE InsertStrOnNewLine(s : Str255; teHdl : TEHandle);
  1216.     
  1217.     VAR
  1218.         sLen    : LONGINT;
  1219.     
  1220.     BEGIN
  1221.         sLen := Length(s) + 1; { Get String length and add 1 for return char to be prepended to string }
  1222.         s[0] := Chr(kReturnChar);
  1223.         TEInsert(Ptr(@s), sLen, teHdl);     { Insert message into TE Rec }
  1224.     END;
  1225.     
  1226. BEGIN
  1227.     myGRec := gATQEntry.globs;
  1228.     i := myGRec^.nextEvt2Proc;
  1229.     IF (myGRec^.indEvtRec[i].evtMsgNum <> 0) THEN    { evtMsgNum is non-zero indicating that a Transition event }
  1230.                                                                                 { has occurred that we haven't processed this one yet }
  1231.     BEGIN
  1232.         WITH myGRec^ DO BEGIN
  1233.             Secs2Date(indEvtRec[i].evtTime, dtRec);
  1234.             dtStr := DateRecToStr(dtRec);
  1235.             if (docTE <> NIL) THEN BEGIN     { there is a window to output to }
  1236.                 err := GetMyStrings(indEvtRec[i].evtMsgNum, strHdl1, strHdl2, strHdl3);
  1237.                 if (err = noErr) THEN BEGIN
  1238.                     InsertStrOnNewLine(strHdl1^^, docTE);                        { Insert message into TE Rec }
  1239.                     TEInsert(Ptr(@dtStr[1]), LONGINT(dtStr[0]), docTE); { Insert dateTime stamp into TE Rec }
  1240.                     
  1241.                     CASE indEvtRec[i].evtMsgNum of
  1242.                         kATTransNameChangeTellTaskMsgNum,
  1243.                         kATTransNameChangeAskTaskMsgNum ,
  1244.                         kATTransCancelNameChangeMsgNum: 
  1245.                         BEGIN
  1246.                             InsertStrOnNewLine(strHdl2^^, docTE);                        { Insert message into TE Rec }
  1247.                             if (indEvtRec[i].evtMsgNum = kATTransCancelNameChangeMsgNum) THEN
  1248.                                 TEInsert(Ptr(@oldFlagName[1]), LONGINT(oldFlagName[0]), docTE)
  1249.                             ELSE
  1250.                                 TEInsert(Ptr(@newFlagName[1]), LONGINT(newFlagName[0]), docTE);
  1251.                         END;
  1252.  
  1253.                         kATTransCableChangeMsgNum :
  1254.                         BEGIN
  1255.                             InsertStrOnNewLine(strHdl2^^, docTE);                        { Insert message into TE Rec }
  1256.                             NumToString(newCableLo, netStr);                            { convert lo cable num to string }
  1257.                             TEInsert(Ptr(@netStr[1]), LONGINT(netStr[0]), docTE);
  1258.                             TEInsert(Ptr(@strHdl3^^[1]), LONGINT(strHdl3^^[0]), docTE);
  1259.                             NumToString(newCableHi, netStr);                            { convert lo cable num to string }
  1260.                             TEInsert(Ptr(@netStr[1]), LONGINT(netStr[0]), docTE);
  1261.                         END;
  1262.                         
  1263.                         kATTransNetworkTransitionMsgNum :
  1264.                         BEGIN
  1265.                             InsertStrOnNewLine(strHdl2^^, docTE);                        { Insert message into TE Rec }
  1266.                         END;
  1267.                     END;    { CASE }
  1268.                 END;        { err == noErr }
  1269.                 indEvtRec[i].evtMsgNum := 0;                            { indicate that we have processed this one }
  1270.                 IF (nextEvt2Proc >= kNumRecs) THEN
  1271.                     nextEvt2Proc := 1
  1272.                 ELSE
  1273.                     nextEvt2Proc := nextEvt2Proc + 1;
  1274.             END;    { docTE <> NIL }
  1275.         END;    { WITH }
  1276.     END; { myGRec^.indEvtRec[i].evtMsgNum <> 0 }
  1277. END; {DoIdle}
  1278.  
  1279.  
  1280. {$S Main}
  1281. PROCEDURE DoKeyDown(event: EventRecord);
  1282.  
  1283. {This is called for any keyDown or autoKey events, except when the
  1284.  Command key is held down. It looks at the frontmost window to decide what
  1285.  to do with the key typed.}
  1286.  
  1287. BEGIN
  1288. END; {DoKeyDown}
  1289.  
  1290.  
  1291. {$S Main}
  1292. PROCEDURE DoContentClick(window: WindowPtr; event: EventRecord);
  1293.  
  1294. {Called when a mouseDown occurs in the content of a window.}
  1295.  
  1296. VAR
  1297.     mouse        : Point;
  1298.     control        : ControlHandle;
  1299.     part, value    : INTEGER;
  1300.     shiftDown    : BOOLEAN;
  1301.     teRect        : Rect;
  1302.  
  1303. BEGIN
  1304.     IF IsAppWindow(window) THEN BEGIN
  1305.         SetPort(window);
  1306.         mouse := event.where;                                            {get the click position}
  1307.         GlobalToLocal(mouse);                                            {convert to local coordinates}
  1308.         {see if we are in the viewRect. if so, we won’t check the controls}
  1309.         GetTERect(window, teRect);
  1310.         part := FindControl(mouse, window, control);
  1311.         WITH DocumentPeek(window)^ DO
  1312.             CASE part OF
  1313.                 0:;                                            {do nothing for viewRect case}
  1314.                 inThumb: BEGIN
  1315.                     value := GetCtlValue(control);
  1316.                     part := TrackControl(control, mouse, NIL);
  1317.                     IF part <> 0 THEN BEGIN
  1318.                         value := value - GetCtlValue(control);
  1319.                         IF value <> 0 THEN
  1320.                             IF control = docVScroll THEN
  1321.                                 TEScroll(0, value * docTE^^.lineHeight, docTE)
  1322.                             ELSE
  1323.                                 TEScroll(value, 0, docTE);
  1324.                     END;
  1325.                 END;
  1326.                 OTHERWISE                                    {must be page or button}
  1327.                     IF control = docVScroll THEN
  1328.                         value := TrackControl(control, mouse, @VActionProc)
  1329.                     ELSE
  1330.                         value := TrackControl(control, mouse, @HActionProc);
  1331.             END;
  1332.     END;
  1333. END; {DoContentClick}
  1334.  
  1335.  
  1336. {$S Main}
  1337. PROCEDURE ResizeWindow(window: WindowPtr);
  1338.  
  1339. {Called when the window has been resized to fix up the controls and content}
  1340.  
  1341. BEGIN
  1342.     WITH window^ DO BEGIN
  1343.         AdjustScrollbars(window, TRUE);
  1344.         AdjustTE(window);
  1345.         InvalRect(portRect);
  1346.     END;
  1347. END; {ResizeWindow}
  1348.  
  1349.  
  1350. {$S Main}
  1351. PROCEDURE GetLocalUpdateRgn(window: WindowPtr; localRgn: RgnHandle);
  1352.  
  1353. {Returns the update region in local coordinates}
  1354.  
  1355. BEGIN
  1356.     CopyRgn(WindowPeek(window)^.updateRgn, localRgn);                        {save old update region}
  1357.     WITH window^.portBits.bounds DO
  1358.         OffsetRgn(localRgn, left, top);                                        {convert to local coords}
  1359. END; {GetLocalUpdateRgn}
  1360.  
  1361.  
  1362. {$S Main}
  1363. PROCEDURE DoGrowWindow(window: WindowPtr; event: EventRecord);
  1364.  
  1365. {Called when a mouseDown occurs in the grow box of an active window. In
  1366.  order to eliminate any 'flicker', we want to invalidate only what is
  1367.  necessary. Since ResizeWindow invalidates the whole portRect, we save
  1368.  the old TE viewRect, intersect it with the new TE viewRect, and
  1369.  remove the result from the update region. However, we must make sure
  1370.  that any old update region that might have been around gets put back.}
  1371.  
  1372. VAR
  1373.     growResult        : LONGINT;
  1374.     tempRect        : Rect;
  1375.     tempRgn            : RgnHandle;
  1376.     ignoreResult    : BOOLEAN;
  1377.  
  1378. BEGIN
  1379.     WITH screenBits.bounds DO
  1380.         SetRect(tempRect, kMinDocDim, kMinDocDim, right, bottom);            {set up limiting values}
  1381.     growResult := GrowWindow(window, event.where, tempRect);
  1382.     IF growResult <> 0 THEN                                                 {see if changed size}
  1383.         WITH DocumentPeek(window)^, window^ DO BEGIN
  1384.             tempRect := docTE^^.viewRect;                                    {save old text box}
  1385.             tempRgn := NewRgn;
  1386.             GetLocalUpdateRgn(window, tempRgn);                                {get localized update region}
  1387.             SizeWindow(window, LoWrd(growResult), HiWrd(growResult), TRUE);
  1388.             ResizeWindow(window);
  1389.             ignoreResult := SectRect(tempRect, docTE^^.viewRect, tempRect);    {find what stayed same}
  1390.             ValidRect(tempRect);                                            {take it out of update}
  1391.             InvalRgn(tempRgn);                                                {put back any prior update}
  1392.             DisposeRgn(tempRgn);
  1393.         END;
  1394. END; {DoGrowWindow}
  1395.  
  1396.  
  1397. {$S Main}
  1398. PROCEDURE DoZoomWindow(window: WindowPtr; part: INTEGER);
  1399.  
  1400. {Called when a mouseClick occurs in the zoom box of an active window.
  1401.  Everything has to get re-drawn here, so we don't mind that
  1402.  ResizeWindow invalidates the whole portRect.}
  1403.  
  1404. BEGIN
  1405.     WITH window^ DO BEGIN
  1406.         EraseRect(portRect);
  1407.         ZoomWindow(window, part, (window = FrontWindow));
  1408.         ResizeWindow(window);
  1409.     END;
  1410. END; {DoZoomWindow}
  1411.  
  1412.  
  1413. {$S Main}
  1414. PROCEDURE DoUpdate(window: WindowPtr);
  1415.  
  1416. {This is called when an update event is received for a window.
  1417.  It calls DrawWindow to draw the contents of an application window,
  1418.  but only if the visRgn is non-empty; for efficiency reasons,
  1419.  not because it is required.}
  1420.  
  1421. BEGIN
  1422.     IF IsAppWindow(window) THEN BEGIN
  1423.         BeginUpdate(window);                    {this sets up the visRgn}
  1424.         IF NOT EmptyRgn(window^.visRgn) THEN    {draw if updating needs to be done}
  1425.             DrawWindow(window);
  1426.         EndUpdate(window);
  1427.     END;
  1428. END; {DoUpdate}
  1429.  
  1430.  
  1431. {$S Main}
  1432. PROCEDURE DoActivate(window: WindowPtr; becomingActive: BOOLEAN);
  1433.  
  1434. {This is called when a window is activated or deactivated.}
  1435.  
  1436. VAR
  1437.     tempRgn, clipRgn    : RgnHandle;
  1438.     growRect            : Rect;
  1439.  
  1440. BEGIN
  1441.     IF IsAppWindow(window) THEN
  1442.         WITH DocumentPeek(window)^ DO
  1443.             IF becomingActive THEN BEGIN
  1444.                 {since we don’t want TEActivate to draw a selection in an area where
  1445.                  we’re going to erase and redraw, we’ll clip out the update region
  1446.                  before calling it.}
  1447.                 tempRgn := NewRgn;
  1448.                 clipRgn := NewRgn;
  1449.                 GetLocalUpdateRgn(window, tempRgn);            {get localized update region}
  1450.                 GetClip(clipRgn);
  1451.                 DiffRgn(clipRgn, tempRgn, tempRgn);            {subtract updateRgn from clipRgn}
  1452.                 SetClip(tempRgn);
  1453.                 TEActivate(docTE);                            {let TE do its thing}
  1454.                 SetClip(clipRgn);                            {restore the full-blown clipRgn}
  1455.                 DisposeRgn(tempRgn);
  1456.                 DisposeRgn(clipRgn);
  1457.  
  1458.                 {the controls need to be redrawn on activation:}
  1459.                 docVScroll^^.contrlVis := kControlVisible;
  1460.                 docHScroll^^.contrlVis := kControlVisible;
  1461.                 InvalRect(docVScroll^^.contrlRect);
  1462.                 InvalRect(docHScroll^^.contrlRect);
  1463.                 {the growbox needs to be redrawn on activation:}
  1464.                 growRect := window^.portRect;
  1465.                 WITH growRect DO BEGIN
  1466.                     top := bottom - kScrollbarAdjust;        {adjust for the scrollbars}
  1467.                     left := right - kScrollbarAdjust;
  1468.                     END;
  1469.                 InvalRect(growRect);
  1470.             END ELSE BEGIN
  1471.                 TEDeactivate(docTE);
  1472.                 {the controls should be hidden immediately on deactivation:}
  1473.                 HideControl(docVScroll);
  1474.                 HideControl(docHScroll);
  1475.                 {the growbox should be changed immediately on deactivation:}
  1476.                 DrawGrowIcon(window);
  1477.             END;
  1478. END; {DoActivate}
  1479.  
  1480.  
  1481. {$S Main}
  1482. PROCEDURE GetGlobalMouse(VAR mouse: Point);
  1483.  
  1484. {Get the global coordinates of the mouse. When you call OSEventAvail
  1485.  it will return either a pending event or a null event. In either case,
  1486.  the where field of the event record will contain the current position
  1487.  of the mouse in global coordinates and the modifiers field will reflect
  1488.  the current state of the modifiers. Another way to get the global
  1489.  coordinates is to call GetMouse and LocalToGlobal, but that requires
  1490.  being sure that thePort is set to a valid port.}
  1491.  
  1492. VAR
  1493.     event    : EventRecord;
  1494.     
  1495. BEGIN
  1496.     IF OSEventAvail(kNoEvents, event) THEN;    {we aren't interested in any events}
  1497.     mouse := event.where;                    {just the mouse position}
  1498. END;
  1499.  
  1500.  
  1501. {$S Main}
  1502. PROCEDURE AdjustCursor(mouse: Point; region: RgnHandle);
  1503.  
  1504. {Change the cursor's shape, depending on its position. This also calculates the region
  1505.  where the current cursor resides (for WaitNextEvent). If the mouse is ever outside of
  1506.  that region, an event is generated, causing this routine to be called. This
  1507.  allows us to change the region to the region the mouse is currently in. If
  1508.  there is more to the event than just “the mouse moved”, we get called before the
  1509.  event is processed to make sure the cursor is the right one. In any (ahem) event,
  1510.  this is called again before we fall back into WNE.}
  1511.  
  1512.  
  1513. VAR
  1514.     window        : WindowPtr;
  1515.     arrowRgn    : RgnHandle;
  1516.     iBeamRgn    : RgnHandle;
  1517.     iBeamRect    : Rect;
  1518.  
  1519. BEGIN
  1520.     window := FrontWindow;    {we only adjust the cursor when we are in front}
  1521.     IF (NOT gInBackground) AND (NOT IsDAWindow(window)) THEN BEGIN
  1522.         {calculate regions for different cursor shapes}
  1523.         arrowRgn := NewRgn;
  1524.         iBeamRgn := NewRgn;
  1525.  
  1526.         {start with a big, big rectangular region}
  1527.         SetRectRgn(arrowRgn, kExtremeNeg, kExtremeNeg, kExtremePos, kExtremePos);
  1528.  
  1529.         {calculate iBeamRgn}
  1530.         IF IsAppWindow(window) THEN BEGIN
  1531.             iBeamRect := DocumentPeek(window)^.docTE^^.viewRect;
  1532.             SetPort(window);                    {make a global version of the viewRect}
  1533.             WITH iBeamRect DO BEGIN
  1534.                 LocalToGlobal(topLeft);
  1535.                 LocalToGlobal(botRight);
  1536.             END;
  1537.             RectRgn(iBeamRgn, iBeamRect);
  1538.             WITH window^.portBits.bounds DO
  1539.                 SetOrigin(-left, -top);
  1540.             SectRgn(iBeamRgn, window^.visRgn, iBeamRgn);
  1541.             SetOrigin(0, 0);
  1542.         END;
  1543.  
  1544.         {subtract other regions from arrowRgn}
  1545.         DiffRgn(arrowRgn, iBeamRgn, arrowRgn);
  1546.         
  1547.         {change the cursor and the region parameter}
  1548.         IF PtInRgn(mouse, iBeamRgn) THEN BEGIN
  1549.             SetCursor(GetCursor(iBeamCursor)^^);
  1550.             CopyRgn(iBeamRgn, region);
  1551.         END ELSE BEGIN
  1552.             SetCursor(arrow);
  1553.             CopyRgn(arrowRgn, region);
  1554.         END;
  1555.  
  1556.         {get rid of our local regions}
  1557.         DisposeRgn(arrowRgn);
  1558.         DisposeRgn(iBeamRgn);
  1559.     END;
  1560. END; {AdjustCursor}
  1561.  
  1562.  
  1563. {$S Main}
  1564. PROCEDURE DoEvent(event: EventRecord);
  1565.  
  1566. {Do the right thing for an event. Determine what kind of event it is, and call
  1567.  the appropriate routines.}
  1568.  
  1569. VAR
  1570.     part, err    : INTEGER;
  1571.     window        : WindowPtr;
  1572.     key            : CHAR;
  1573.     ignore        : BOOLEAN;
  1574.     aPoint        : Point;
  1575.  
  1576. BEGIN
  1577.     CASE event.what OF
  1578.         nullEvent:
  1579.             DoIdle;
  1580.         mouseDown: BEGIN
  1581.             part := FindWindow(event.where, window);
  1582.             CASE part OF
  1583.                 inMenuBar: BEGIN
  1584.                     AdjustMenus;
  1585.                     DoMenuCommand(MenuSelect(event.where));
  1586.                 END;
  1587.                 inSysWindow:
  1588.                     SystemClick(event, window);
  1589.                 inContent:
  1590.                     IF window <> FrontWindow THEN BEGIN
  1591.                         SelectWindow(window);
  1592.                         {DoEvent(event);}    {use this line for "do first click"}
  1593.                     END ELSE
  1594.                         DoContentClick(window, event);
  1595.                 inDrag:
  1596.                     DragWindow(window, event.where, screenBits.bounds);
  1597.                 inGrow:
  1598.                     DoGrowWindow(window, event);
  1599.                 inGoAway:
  1600.                     IF TrackGoAway(window, event.where) THEN
  1601.                         ignore := DoCloseWindow(window);        {we don't care if cancelled}
  1602.                 inZoomIn, inZoomOut:
  1603.                     IF TrackBox(window, event.where, part) THEN
  1604.                         DoZoomWindow(window, part);
  1605.             END;
  1606.         END;
  1607.         keyDown, autoKey: BEGIN
  1608.             key := CHR(BAnd(event.message, charCodeMask));
  1609.             IF BAnd(event.modifiers, cmdKey) <> 0 THEN BEGIN    {Command key down}
  1610.                 IF event.what = keyDown THEN BEGIN
  1611.                     AdjustMenus;            {enable/disable/check menu items properly}
  1612.                     DoMenuCommand(MenuKey(key));
  1613.                 END;
  1614.             END;
  1615.         END;                                {call DoActivate with the window and...}
  1616.         activateEvt:                        {TRUE for activate, FALSE for deactivate}
  1617.             DoActivate(WindowPtr(event.message), BAnd(event.modifiers, activeFlag) <> 0);
  1618.         updateEvt:                            {call DoUpdate with the window to update}
  1619.             DoUpdate(WindowPtr(event.message));
  1620.         {1.01 - It is not a bad idea to at least call DIBadMount in response
  1621.          to a diskEvt, so that the user can format a floppy.}
  1622.         diskEvt:
  1623.             IF HiWrd(event.message) <> noErr THEN BEGIN
  1624.                 SetPt(aPoint, kDILeft, kDITop);
  1625.                 err := DIBadMount(aPoint, event.message);
  1626.             END;
  1627.         kOSEvent:
  1628.             CASE BAnd(BRotL(event.message, 8), $FF) OF    {high byte of message}
  1629.                 kMouseMovedMessage:
  1630.                     DoIdle;                    {mouse moved is also an idle event}
  1631.                 kSuspendResumeMessage: BEGIN
  1632.                     gInBackground := BAnd(event.message, kResumeMask) = 0;
  1633.                     DoActivate(FrontWindow, NOT gInBackground);
  1634.                 END;
  1635.             END;
  1636.     END;
  1637. END; {DoEvent}
  1638.  
  1639.  
  1640. {$S Main}
  1641. PROCEDURE EventLoop;
  1642.  
  1643. {Get events forever, and handle them by calling DoEvent.
  1644.  Also call AdjustCursor each time through the loop.}
  1645.  
  1646. VAR
  1647.     cursorRgn    : RgnHandle;
  1648.     gotEvent    : BOOLEAN;
  1649.     event        : EventRecord;
  1650.     mouse        : Point;
  1651.  
  1652. BEGIN
  1653.     cursorRgn := NewRgn;        {we'll pass an empty region to WNE the first time thru}
  1654.     REPEAT
  1655.         IF gHasWaitNextEvent THEN BEGIN    {put us 'asleep' forever under MultiFinder}
  1656.             GetGlobalMouse(mouse);        {since we might go to sleep}
  1657.             AdjustCursor(mouse, cursorRgn);
  1658.             gotEvent := WaitNextEvent(everyEvent, event, GetSleep, cursorRgn);
  1659.         END ELSE BEGIN
  1660.             SystemTask;                    {must be called if using GetNextEvent}
  1661.             gotEvent := GetNextEvent(everyEvent, event);
  1662.         END;
  1663.         IF gotEvent THEN BEGIN
  1664.             AdjustCursor(event.where, cursorRgn);    {make sure we have the right cursor}
  1665.             DoEvent(event);                {Handle the event only if for us.}
  1666.             END
  1667.         ELSE
  1668.             DoIdle;
  1669.         {If you are using modeless dialogs that have editText items,
  1670.          you will want to call IsDialogEvent to give the caret a chance
  1671.          to blink, even if WNE/GNE returned FALSE. However, check FrontWindow
  1672.          for a non-NIL value before calling IsDialogEvent.}
  1673.     UNTIL FALSE;    {loop forever}
  1674. END; {EventLoop}
  1675.  
  1676.  
  1677. PROCEDURE _DataInit; EXTERNAL;
  1678.  
  1679. {This routine is automatically linked in by the MPW Linker. This external
  1680.  reference to it is done so that we can unload its segment, %A5Init.}
  1681.  
  1682.  
  1683. {$S Main}
  1684. BEGIN
  1685.     UnloadSeg(@_DataInit);    {note that _DataInit must not be in Main!}
  1686.     
  1687.     {1.01 - call to ForceEnvirons removed}
  1688.     {If you have stack requirements that differ from the default,
  1689.      then you could use SetApplLimit to increase StackSpace at 
  1690.      this point, before calling MaxApplZone.}
  1691.      
  1692.     MaxApplZone;            {expand the heap so code segments load at the top}
  1693.  
  1694.     Initialize;                {initialize the program}
  1695.     UnloadSeg(@Initialize);    {note that Initialize must not be in Main!}
  1696.  
  1697.     EventLoop;                {call the main event loop}
  1698. END.
  1699.